/**
 * WooCommerce Enhanced Functions
 * WooCommerce增强功能脚本
 * 
 * @package WP Bootstrap Woo
 */

(function($) {
    'use strict';

    // 全局变量
    const WBW_WooCommerce = {
        init: function() {
            this.setupAjaxCart();
            this.setupProductActions();
            this.setupWishlist();
            this.setupCompare();
            this.setupQuickView();
            this.setupNotifications();
        },

        // Ajax购物车功能
        setupAjaxCart: function() {
            // 添加到购物车Ajax处理
            $(document).on('click', '.ajax_add_to_cart', function(e) {
                e.preventDefault();
                
                const $button = $(this);
                const productId = $button.data('product_id');
                const quantity = $button.data('quantity') || 1;
                
                // 显示加载状态
                $button.addClass('loading').prop('disabled', true);
                const originalText = $button.find('span').text();
                $button.find('span').text('Adding...');
                
                // Ajax请求
                $.ajax({
                    url: wbw_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wbw_add_to_cart',
                        product_id: productId,
                        quantity: quantity,
                        nonce: wbw_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // 更新购物车计数
                            WBW_WooCommerce.updateCartCount(response.data.cart_count);
                            
                            // 显示成功消息
                            WBW_WooCommerce.showNotification('Product added to cart!', 'success');
                            
                            // 更新按钮状态
                            $button.find('span').text('Added!');
                            
                            // 恢复按钮
                            setTimeout(() => {
                                $button.removeClass('loading').prop('disabled', false);
                                $button.find('span').text(originalText);
                            }, 2000);
                            
                        } else {
                            WBW_WooCommerce.showNotification(response.data.message, 'error');
                            $button.removeClass('loading').prop('disabled', false);
                            $button.find('span').text(originalText);
                        }
                    },
                    error: function() {
                        WBW_WooCommerce.showNotification('Something went wrong. Please try again.', 'error');
                        $button.removeClass('loading').prop('disabled', false);
                        $button.find('span').text(originalText);
                    }
                });
            });

            // 移除购物车商品
            $(document).on('click', '.remove-cart-item', function(e) {
                e.preventDefault();
                
                const $button = $(this);
                const cartItemKey = $button.data('cart_item_key');
                
                $.ajax({
                    url: wbw_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wbw_remove_cart_item',
                        cart_item_key: cartItemKey,
                        nonce: wbw_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $button.closest('.cart-item').fadeOut(() => {
                                $(this).remove();
                            });
                            WBW_WooCommerce.updateCartCount(response.data.cart_count);
                            WBW_WooCommerce.showNotification('Item removed from cart.', 'info');
                        }
                    }
                });
            });
        },

        // 产品操作功能
        setupProductActions: function() {
            // 数量增减
            $(document).on('click', '.qty-btn', function() {
                const $input = $(this).siblings('input[type="number"]');
                const currentVal = parseInt($input.val()) || 0;
                const isIncrease = $(this).hasClass('qty-increase');
                const min = parseInt($input.attr('min')) || 1;
                const max = parseInt($input.attr('max')) || 999;
                
                let newVal = isIncrease ? currentVal + 1 : currentVal - 1;
                newVal = Math.max(min, Math.min(max, newVal));
                
                $input.val(newVal).trigger('change');
            });

            // 变体产品选择
            $(document).on('change', '.variation-select', function() {
                const $form = $(this).closest('form');
                WBW_WooCommerce.updateVariationPrice($form);
            });
        },

        // 愿望清单功能
        setupWishlist: function() {
            $(document).on('click', '.btn-wishlist', function(e) {
                e.preventDefault();
                
                const $button = $(this);
                const productId = $button.data('product-id');
                const isInWishlist = $button.hasClass('in-wishlist');
                
                $button.addClass('loading');
                
                $.ajax({
                    url: wbw_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: isInWishlist ? 'wbw_remove_from_wishlist' : 'wbw_add_to_wishlist',
                        product_id: productId,
                        nonce: wbw_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $button.toggleClass('in-wishlist');
                            const message = isInWishlist ? 'Removed from wishlist' : 'Added to wishlist';
                            WBW_WooCommerce.showNotification(message, 'success');
                            
                            // 更新愿望清单计数
                            $('.wishlist-count').text('(' + response.data.wishlist_count + ')');
                        }
                        $button.removeClass('loading');
                    },
                    error: function() {
                        $button.removeClass('loading');
                        WBW_WooCommerce.showNotification('Something went wrong.', 'error');
                    }
                });
            });
        },

        // 比较功能
        setupCompare: function() {
            $(document).on('click', '.btn-compare', function(e) {
                e.preventDefault();
                
                const $button = $(this);
                const productId = $button.data('product-id');
                
                $button.addClass('loading');
                
                $.ajax({
                    url: wbw_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wbw_add_to_compare',
                        product_id: productId,
                        nonce: wbw_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            WBW_WooCommerce.showNotification('Added to compare list', 'success');
                        } else {
                            WBW_WooCommerce.showNotification(response.data.message, 'info');
                        }
                        $button.removeClass('loading');
                    }
                });
            });
        },

        // 快速查看功能
        setupQuickView: function() {
            $(document).on('click', '.btn-quick-view', function(e) {
                e.preventDefault();
                
                const productId = $(this).data('product-id');
                WBW_WooCommerce.openQuickView(productId);
            });
        },

        // 打开快速查看模态框
        openQuickView: function(productId) {
            // 创建模态框HTML
            const modalHtml = `
                <div class="quick-view-modal" id="quickViewModal">
                    <div class="modal-backdrop"></div>
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4>Quick View</h4>
                            <button type="button" class="modal-close">&times;</button>
                        </div>
                        <div class="modal-body">
                            <div class="loading-spinner">Loading...</div>
                        </div>
                    </div>
                </div>
            `;
            
            $('body').append(modalHtml);
            
            // 加载产品数据
            $.ajax({
                url: wbw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'wbw_quick_view',
                    product_id: productId,
                    nonce: wbw_ajax.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $('#quickViewModal .modal-body').html(response.data.html);
                    } else {
                        $('#quickViewModal .modal-body').html('<p>Failed to load product information.</p>');
                    }
                }
            });
            
            // 关闭模态框事件
            $(document).on('click', '#quickViewModal .modal-close, #quickViewModal .modal-backdrop', function() {
                $('#quickViewModal').remove();
            });
        },

        // 通知系统
        setupNotifications: function() {
            // 创建通知容器
            if (!$('#wbw-notifications').length) {
                $('body').append('<div id="wbw-notifications"></div>');
            }
        },

        // 显示通知
        showNotification: function(message, type = 'info') {
            const notificationId = 'notification-' + Date.now();
            const notification = `
                <div class="wbw-notification ${type}" id="${notificationId}">
                    <div class="notification-content">
                        <span class="notification-message">${message}</span>
                        <button type="button" class="notification-close">&times;</button>
                    </div>
                </div>
            `;
            
            $('#wbw-notifications').append(notification);
            
            // 自动消失
            setTimeout(() => {
                $('#' + notificationId).fadeOut(() => {
                    $(this).remove();
                });
            }, 5000);
            
            // 手动关闭
            $(document).on('click', `#${notificationId} .notification-close`, function() {
                $('#' + notificationId).fadeOut(() => {
                    $(this).remove();
                });
            });
        },

        // 更新购物车计数
        updateCartCount: function(count) {
            $('.cart-count, .cart-counter').text('(' + count + ')');
        },

        // 更新变体价格
        updateVariationPrice: function($form) {
            const formData = $form.serialize();
            
            $.ajax({
                url: wbw_ajax.ajax_url,
                type: 'POST',
                data: formData + '&action=wbw_get_variation_price&nonce=' + wbw_ajax.nonce,
                success: function(response) {
                    if (response.success) {
                        $form.find('.price').html(response.data.price_html);
                        $form.find('.stock-status').html(response.data.availability_html);
                    }
                }
            });
        }
    };

    // 文档加载完成后初始化
    $(document).ready(function() {
        WBW_WooCommerce.init();
    });

    // 全局暴露
    window.WBW_WooCommerce = WBW_WooCommerce;

})(jQuery);